const  methods = require('methods')
const Layer = require('./layer')

function Route(){
    this.stack = []
}

// 5.遍历执行所有处理函数，out：去往外层
Route.prototype.dispatch = function(req,res,out){
    // 遍历内存 stack
    let index = 0
    const method = req.method.toLowerCase()
    const next = ()=>{
        if(index >= this.stack.length){
            return out() // 遍历结束时遍历外层
        }
        const layer = this.stack[index++]
        if(layer.method === method){
            return layer.handler(req,res,next)
        }
        next()
    }
    next()
} 
// 1.接收多个处理函数的中间件
methods.forEach((method)=>{
    Route.prototype[method] = function (path,handlers){
        handlers.forEach(handler=>{
            const  layer = new Layer(path,handler)
            layer.method = method
            this.stack.push(layer)
        })
    }
})

module.exports = Route